import { useState, useEffect } from 'react'
import { LeftOutline } from 'antd-mobile-icons'
import { useNavigate, useLocation } from 'react-router-dom'
import './kdqr.scss'

interface SelectedItem {
  id: number
  name: string
  price: number
  quantity: number
  category: string
  type: '药品' | '检查' | '检验'
}

interface CartItem {
  id: number
  name: string
  price: number
  quantity: number
  category: string
}

function Kdqr() {
  const navigate = useNavigate()
  const location = useLocation()
  const [reason, setReason] = useState('')
  const [selectedPatient] = useState('王小柯')
  const [selectedItems, setSelectedItems] = useState<SelectedItem[]>([])

  // 从路由状态或本地存储获取已选择的项目
  useEffect(() => {
    // 尝试从路由状态获取数据
    if (location.state && location.state.selectedItems) {
      setSelectedItems(location.state.selectedItems)
    } else {
      // 从本地存储获取数据
      const savedCartItems = localStorage.getItem('kdxq_cartItems')
      const savedExamItems = localStorage.getItem('kdxq_examItems')
      const savedTestItems = localStorage.getItem('kdxq_testItems')
      
      let allSelectedItems: SelectedItem[] = []
      
      if (savedCartItems) {
        const cartItems = JSON.parse(savedCartItems)
        const selectedCartItems = cartItems
          .filter((item: CartItem) => item.quantity > 0)
          .map((item: CartItem) => ({
            id: item.id,
            name: item.name,
            price: item.price,
            quantity: item.quantity,
            category: item.category,
            type: '药品' as const
          }))
        allSelectedItems = [...allSelectedItems, ...selectedCartItems]
      }
      
      if (savedExamItems) {
        const examItems = JSON.parse(savedExamItems)
        const selectedExamItems = examItems
          .filter((item: CartItem) => item.quantity > 0)
          .map((item: CartItem) => ({
            id: item.id,
            name: item.name,
            price: item.price,
            quantity: item.quantity,
            category: item.category,
            type: '检查' as const
          }))
        allSelectedItems = [...allSelectedItems, ...selectedExamItems]
      }
      
      if (savedTestItems) {
        const testItems = JSON.parse(savedTestItems)
        const selectedTestItems = testItems
          .filter((item: CartItem) => item.quantity > 0)
          .map((item: CartItem) => ({
            id: item.id,
            name: item.name,
            price: item.price,
            quantity: item.quantity,
            category: item.category,
            type: '检验' as const
          }))
        allSelectedItems = [...allSelectedItems, ...selectedTestItems]
      }
      
      setSelectedItems(allSelectedItems)
    }
  }, [location.state])

  // 计算总价
  const totalPrice = selectedItems.reduce((sum, item) => sum + (item.price * item.quantity), 0)

  // 获取项目类型图标
  const getTypeIcon = (type: string) => {
    switch (type) {
      case '药品':
        return { icon: '药', color: '#1890ff' }
      case '检查':
        return { icon: '查', color: '#fa8c16' }
      case '检验':
        return { icon: '验', color: '#ff4d4f' }
      default:
        return { icon: '药', color: '#1890ff' }
    }
  }

  // 获取项目单位
  const getQuantityUnit = (type: string) => {
    switch (type) {
      case '药品':
        return '剂'
      case '检查':
      case '检验':
        return '次'
      default:
        return '项'
    }
  }

  // 获取项目标签
  const getItemTags = (item: SelectedItem) => {
    const tags = []
    if (item.type === '药品') {
      tags.push({ text: '处方药', color: '#1890ff' })
      if (item.name.includes('新冠预防')) {
        tags.push({ text: '限购5剂', color: '#ff4d4f' })
      }
    }
    return tags
  }

  const handleConfirm = () => {
    if (reason.length < 20) {
      alert('申请原因不能少于20字')
      return
    }
    // 处理确认申请逻辑
    console.log('确认申请', { reason, selectedItems, totalPrice })
    // 可以跳转到成功页面或返回上一页
    navigate(-1)
  }

  return (
    <div className='kdqr'>
      {/* 顶部导航 */}
      <div className='kdqr-top'>
        <span><LeftOutline className='kdqr-top-left' onClick={() => navigate(-1)} /></span>
        <span className='kdqr-top-title'>开单确认</span>
      </div>

      <div className='kdqr-content'>
        {/* 申请信息 */}
        <div className='info-section'>
          <div className='section-title'>申请信息</div>
          <div className='info-item'>
            <span className='info-label'>申请医院</span>
            <span className='info-value'>四川省保健院北苑</span>
          </div>
          <div className='info-item clickable' onClick={() => console.log('选择申请人')}>
            <span className='info-label'>申请人</span>
            <span className='info-value'>
              {selectedPatient}
              <span className='arrow'></span>
            </span>
          </div>
        </div>

        {/* 申请原因 */}
        <div className='reason-section'>
          <div className='section-title'>申请原因*</div>
          <div className='reason-input-container'>
            <textarea
              className='reason-input'
              placeholder='请输入项目申请原因用于医生更准确判断，不少于20字'
              value={reason}
              onChange={(e) => setReason(e.target.value)}
              maxLength={200}
            />
            <div className='char-count'>{reason.length} / 200</div>
          </div>
        </div>

        {/* 申请项目 */}
        <div className='items-section'>
          <div className='section-title'>申请项目</div>
          {selectedItems.length === 0 ? (
            <div className='empty-state'>
              <div className='empty-text'>暂无选择的项目</div>
              <button 
                className='back-btn' 
                onClick={() => navigate('/kdxq')}
              >
                返回选择项目
              </button>
            </div>
          ) : (
            <>
              <div className='items-list'>
                {selectedItems.map((item) => {
                  const typeInfo = getTypeIcon(item.type)
                  const unit = getQuantityUnit(item.type)
                  const tags = getItemTags(item)
                  
                  return (
                    <div key={item.id} className='item-card'>
                      <div className='item-header'>
                        <div className='item-icon' style={{ backgroundColor: typeInfo.color }}>
                          {typeInfo.icon}
                        </div>
                        <div className='item-info'>
                          <div className='item-name'>{item.name}</div>
                          <div className='item-quantity'>数量: {item.quantity}{unit}</div>
                          {tags.length > 0 && (
                            <div className='item-tags'>
                              {tags.map((tag, tagIndex) => (
                                <span
                                  key={tagIndex}
                                  className='item-tag'
                                  style={{ color: tag.color, borderColor: tag.color }}
                                >
                                  {tag.text}
                                </span>
                              ))}
                            </div>
                          )}
                        </div>
                        <div className='item-price'>¥ {item.price.toFixed(2)}</div>
                      </div>
                    </div>
                  )
                })}
              </div>
              <div className='total-summary'>
                <span className='total-label'>合计:</span>
                <span className='total-price'>¥ {totalPrice.toFixed(2)}</span>
              </div>
            </>
          )}
        </div>
      </div>

      {/* 确认按钮 */}
      <div className='confirm-section'>
        <button 
          className='confirm-btn'
          onClick={handleConfirm}
          disabled={reason.length < 20 || selectedItems.length === 0}
        >
          确认申请
        </button>
      </div>
    </div>
  )
}

export default Kdqr
